package cn.easybuy.util;

import cn.easybuy.pojo.News;
import cn.easybuy.pojo.Product;
import cn.easybuy.pojo.ProductCategory;
import cn.easybuy.service.news.NewsService;
import cn.easybuy.service.product.ProductService;
import cn.easybuy.service.productcategory.ProCategoryService;
import cn.easybuy.vo.ProductCategoryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.List;

@Component //组件
public class AppInit implements ApplicationRunner {

    @Autowired
    private ServletContext servletContext;
    @Autowired
    private NewsService newsService;
    @Autowired
    private ProCategoryService proCategoryService;
    @Autowired
    private ProductService productService;

    /**
     * SpringBootApplication:启动时运行
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<News> news = newsService.list(new QueryWrapper<News>().orderByDesc("createTime").last(" limit 5"));
        List<ProductCategoryVo> productCategoryVoList = new ArrayList<>();
        pcv(0, 1, productCategoryVoList);
        servletContext.setAttribute("news",news);
        servletContext.setAttribute("productCategoryVoList",productCategoryVoList);
    }

    //递归
    public void pcv(Integer parentId,Integer type, List<ProductCategoryVo> productCategoryVoList){
        //结束递归的条件
        if(type==4){
            return;
        }
        //重复做的事情
        //1、商品分类
        List<ProductCategory> productCategoryList = proCategoryService.list(new QueryWrapper<ProductCategory>().eq("parentId",parentId).eq("type", type));
        //2、遍历商品分类
        for(ProductCategory productCategory : productCategoryList){
            ProductCategoryVo productCategoryVo = new ProductCategoryVo();
            productCategoryVo.setProductCategory(productCategory);
            if (productCategory.getType() == 1){
                //查询商品分类
                List<Product> productList = productService.list(new QueryWrapper<Product>().orderByDesc("id")
                                                            .eq("categoryLevel1Id",productCategory.getId())
                                                            .last("limit 6"));
                productCategoryVo.setProductList(productList);
            }

            //递归调用
            pcv(productCategory.getId(),
                    type+1,productCategoryVo.getProductCategoryVoList());
            productCategoryVoList.add(productCategoryVo);
        }
    }
}